package com.user.provider.service;

import com.dl.common.redis.SMSCacheKeyBuilder;
import com.dl.live.util.ConvertBeanUtil;
import com.dl.user.dto.UserDTO;
import com.user.provider.entity.SmsDO;
import com.user.provider.entity.UserDO;
import com.user.provider.mapper.SmsMapper;
import com.user.provider.mapper.UserMapper;
import com.user.provider.util.UserRedisKeyBuilder;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
public class UserService {

    @Resource
    private Logger logger = LoggerFactory.getLogger(UserService.class);

    @Resource
    private RedisTemplate <String, Object> redisTemplate;

    @Resource
    private UserRedisKeyBuilder userRedisKeyBuilder;

    @Resource
    private UserMapper userMapper;

    @Resource
    private SMSCacheKeyBuilder smsCacheKeyBuilder;

    @Resource
    private SmsMapper smsMapper;

    public UserDTO getUserByID(Long userId){
        //校验参数是否为空
        if (userId == null && userId <0){
            return null;
        }
        UserDTO userDTO = new UserDTO();
        //从redis中查询用户信息
            //构建Redis的key
        String userInfoKey = userRedisKeyBuilder.buildUserKey(userId);
        userDTO = (UserDTO) redisTemplate.opsForValue().get(userInfoKey);
        //如果Redis存在用户信息，直接返回
        if (userDTO != null){
            return userDTO;
        }else if (null != userDTO && userDTO.getUserId()<0){
            return null;
        }
        //如果Redis中不存在用户信息，从数据库中查询用户信息
        //查询用户
        UserDO userDO = userMapper.selectById(userId);
        if (userDO != null){
            userDTO = ConvertBeanUtil.convertBean(userDO, UserDTO.class);
            redisTemplate.opsForValue().set(userInfoKey, userDTO,30, TimeUnit.MINUTES);
            return userDTO;
        }else {
            //如果数据库没有数据
            /**
             * 缓存击穿，避免频繁查询数据库中不存在的数据
             * 1.设置一个默认值，比如空对象或者空字符串
             * 2.布隆过滤器
             */
            UserDTO notExitUser = new UserDTO();
            notExitUser.setUserId(-1L);
            redisTemplate.opsForValue().set(userInfoKey, notExitUser,30, TimeUnit.MINUTES);
            return null;
        }
    }

    public boolean sendLoginCode(String mobile) {
        //校验参数
        if (!StringUtils.hasText(mobile)) {
            return false;
        }
        //生成和手机号相关联的RedisKey
        String smsCodeKey = smsCacheKeyBuilder.buildSmsLoginCodeKey(mobile);
        //去Redis查询有没有发送过验证码
        Object smsRecord = redisTemplate.opsForValue().get(smsCodeKey);
        if (smsRecord != null) {
            logger.info("手机号：{}，发送验证码：{}", mobile, smsRecord);
            return false;
        }
        //如果没有，发送验证码并保存到Redis
        int smsCode = new Random().nextInt(1000, 9999);
        logger.info("生成验证码：{}",smsCode);
        redisTemplate.opsForValue().set(smsCodeKey, smsCode, 30, TimeUnit.SECONDS);
        //发送验证码
        boolean sendSMS = true;
        //保存短信记录
        insertSMSRecord(mobile, smsCode);
        return  true;
    }

        private boolean sendSms(String mobile, int smsCode){
            return true;
        }


        private void insertSMSRecord(String mobile,int smsCode) {

        SmsDO smsDO = new SmsDO();
        //TODO 生成记录ID
        smsDO.setCode(smsCode);
        smsDO.setPhone(mobile);
        smsMapper.insert(smsDO);
    }
}
